<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="商家名称" prop="shopName">
        <el-input
          v-model="queryParams.shopName"
          placeholder="请输入商家名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="商品名称" prop="prodName">
        <el-input
          v-model="queryParams.prodName"
          placeholder="请输入商品名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="审核状态" prop="isValid">
        <el-select v-model="queryParams.isValid" size="small" clearable>
          <el-option label="无效" value="0" />
          <el-option label="审核通过" value="1" />
          <el-option label="审核中" value="2" />
          <el-option label="已拒绝" value="3" />
        </el-select>
      </el-form-item>
      <el-form-item label="购买有效期 " prop="purchasePeriod">
        <el-date-picker clearable size="small"
          v-model="queryParams.purchasePeriod"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择购买有效期 ">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="兑换有效期 " prop="exchangePeriod">
        <el-date-picker clearable size="small"
          v-model="queryParams.exchangePeriod"
          type="date"
          value-format="yyyy-MM-dd"
          placeholder="选择兑换有效期 ">
        </el-date-picker>
      </el-form-item>
      <el-form-item label="创建时间" prop="createdTime">
        <el-date-picker clearable size="small"
          v-model="dateRange"
          type="daterange"
          value-format="yyyy-MM-dd"
          start-placeholder="开始时间"
          end-placeholder="结束时间">
        </el-date-picker>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['union:product:add']"
        >新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['union:product:edit']"
        >修改</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="productList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="商品主图" align="center" prop="prod_image">
        <template slot-scope="scope">
          <el-image lazy :src="scope.row.prod_image" :preview-src-list="[scope.row.prod_image]">
            <div slot="placeholder" class="image-slot">
              加载中 <span class="dot">...</span>
            </div>
          </el-image>
        </template>
      </el-table-column>
      <el-table-column label="商品名称" align="center" prop="prod_name" />
      <el-table-column label="店铺名称" align="center" prop="shop_name" />
      <el-table-column label="审核状态" align="center" prop="is_valid">
        <template slot-scope="scope">
          <el-select v-model="scope.row.is_valid" size="small" @change="handleChangeValid(scope.row, scope.$index)">
            <el-option label="无效" value="0" />
            <el-option label="审核通过" value="1" />
            <el-option label="审核中" value="2" />
            <el-option label="已拒绝" value="3" />
          </el-select>
        </template>
      </el-table-column>
      <el-table-column label="购买有效期 " align="center" prop="purchase_period" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.purchase_period, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="兑换有效期 " align="center" prop="exchange_period" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.exchange_period, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="最大可兑换数量 " align="center" prop="max_exchange_count" />
      <el-table-column label="购买所需的积分" align="center" prop="prod_score" />
      <el-table-column label="创建时间" align="center" prop="created_time" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.created_time, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['union:product:edit']"
          >修改</el-button>

          <el-button
            size="mini"
            type="text"
            icon="el-icon-share"
            @click="handleLog(scope.row)"
            v-hasPermi="['union:product:edit']"
          >操作日志</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改联盟商家积分商品对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="180px">
        <el-form-item v-if="form.prod_id === null" label="店铺名称" prop="shopId">
          <el-select
            v-model="form.shopId"
            placeholder="请选择店铺"
            clearable
            filterable
            remote
            reserve-keyword
            :remote-method="getShopList">
            <el-option
              v-for="item in shopOptions"
              :key="item.shopId"
              :label="item.shopName"
              :value="item.shopId">
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="商品名称" prop="prodName">
          <el-input v-model="form.prodName" placeholder="请输入商品名称" />
        </el-form-item>
        <el-form-item label="商品主图">
          <el-upload
            name="file"
            drag
            accept="image/*"
            :limit="1"
            :action="upload.uploadToOss"
            :headers="upload.uploadHeaders"
            :onError="uploadError"
            :onSuccess="uploadSuccess">
            <img v-if="form.prodImage" :src="form.prodImage" :width="200" />
            <i v-else class="el-icon-upload"></i>
            <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
          </el-upload>
        </el-form-item>
        <el-form-item label="商品说明" prop="prodExplain">
          <el-input type="textarea" v-model="form.prodExplain" placeholder="请输入商品说明" />
        </el-form-item>
        <el-form-item label="使用规则" prop="prodRemark">
          <el-input v-model="form.prodRemark" placeholder="请输入使用规则" />
        </el-form-item>
        <el-form-item label="购买有效期 " prop="purchasePeriod">
          <el-date-picker clearable size="small"
            v-model="form.purchasePeriod"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择购买有效期 ">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="兑换有效期 " prop="exchangePeriod">
          <el-date-picker clearable size="small"
            v-model="form.exchangePeriod"
            type="date"
            value-format="yyyy-MM-dd"
            placeholder="选择兑换有效期 ">
          </el-date-picker>
        </el-form-item>
        <el-form-item label="最大可兑换数量 " prop="maxExchangeCount">
          <el-input-number :min="1" v-model="form.maxExchangeCount" placeholder="请输入最大可兑换数量 " />
        </el-form-item>
        <el-form-item label="购买所需的积分" prop="prodScore">
          <el-input-number :min="1" v-model="form.prodScore" placeholder="请输入购买所需的积分" />
        </el-form-item>
        <el-form-item label="是否有效" prop="isValid">
          <el-radio-group v-model="form.isValid">
            <el-radio label="0">无效</el-radio>
            <el-radio label="1">审核通过</el-radio>
            <el-radio label="2">审核中</el-radio>
            <el-radio label="3">审核拒绝</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="预计单份获得金额" prop="prodPrice">
          <el-input v-model="form.prodPrice" placeholder="请输入预计单份获得金额" />
        </el-form-item>
        <el-form-item label="审核描述" prop="desc">
          <el-input type="textarea" v-model="form.desc" placeholder="请输入审核描述" />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <el-dialog title="操作日志" :visible.sync="logOpen" width="800px" append-to-body>
      <el-table v-loading="loading" :data="logList">
        <el-table-column label="操作人" align="center" prop="nick_name" />
        <el-table-column label="操作状态" align="center" prop="status">
          <template slot-scope="scope">
            <p v-for="v in JSON.parse(scope.row.status)" v-html="v"></p>
          </template>
        </el-table-column>
        <el-table-column label="操作时间" align="center" prop="created_at" />
      </el-table>

      <pagination
        v-show="logTotal>0"
        :total="logTotal"
        :page.sync="logParams.pageNum"
        :limit.sync="logParams.pageSize"
        @pagination="handleLog"
      />
    </el-dialog>
  </div>
</template>

<script>
import { listProduct, getProduct, changeProdStatus, addProduct, updateProduct, listProductLog } from "@/api/union/product";
import ImageUpload from '@/components/ImageUpload';
import { getShopList } from '@/api/app/messageDefine'
import { getToken } from '@/utils/auth'

export default {
  name: "Product",
  components: {
    ImageUpload,
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      logTotal: 0,
      // 联盟商家积分商品表格数据
      productList: [],
      logList: [],
      tableIsValid: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      logOpen: false,
      dateRange: [],
      shopOptions: [],
      upload: {
        uploadToOss: process.env.VUE_APP_BASE_API + "/common/uploadToOss",
        uploadHeaders: {
          Authorization: "Bearer " + getToken()
        }
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: "updated_time",
        isAsc: "desc",
      },
      logParams: {
        pageNum: 1,
        pageSize: 10,
        orderByColumn: "created_at",
        isAsc: "desc",
        prodId: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        shopId: [
          { required: true, message: "请选择店铺", trigger: "blur" }
        ],
        prodName: [
          { required: true, message: "商品名称不能为空", trigger: "blur" }
        ],
        purchasePeriod: [
          { required: true, message: "购买有效期 不能为空", trigger: "blur" }
        ],
        exchangePeriod: [
          { required: true, message: "兑换有效期 不能为空", trigger: "blur" }
        ],
        maxExchangeCount: [
          { required: true, message: "最大可兑换数量 不能为空", trigger: "blur" }
        ],
        prodPrice: [
          { required: true, message: "预计单份获得金额不能为空", trigger: "blur" }
        ],
      }
    };
  },
  created() {
    this.getList();
  },
  methods: {
    /** 查询联盟商家积分商品列表 */
    getList() {
      this.loading = true;

      listProduct(this.addDateRange(this.queryParams, this.dateRange)).then(response => {
        this.productList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        prod_id: null,
        shop_id: null,
        prod_name: null,
        prod_image: null,
        prod_explain: null,
        prod_remark: null,
        purchase_period: null,
        exchange_period: null,
        max_exchange_count: null,
        prod_score: null,
        is_valid: "1",
        prod_price: null,
        desc: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = []
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.prodId)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加联盟商家积分商品";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const prodId = row.prod_id || this.ids
      getProduct(prodId).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改联盟商家积分商品";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.prodId != null) {
            updateProduct(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addProduct(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },

    handleLog(row) {
      this.logOpen = true
      this.loading = true
      if (row.prod_id)
        this.logParams.prodId = row.prod_id

      listProductLog(this.logParams).then(response => {
        this.logList = response.rows
        this.logTotal = response.total
        this.loading = false
      })
    },

    handleChangeValid(row, index) {
      let prodId = row.prod_id, isValid = row.is_valid
      this.loading = true;
      changeProdStatus(prodId, isValid).then(response => {
        if (response.code === 200) {
          this.msgSuccess("修改成功");
        }

        this.loading = false;
      })
    },
    getShopList(query) {
      if (query !== '') {
        setTimeout(() => {
          getShopList(query).then(response => {
            this.shopOptions = response.data
          })
        }, 200)
      }
    },
    uploadSuccess (response, file, fileList) {
      this.form.prodImage = response.data
    },
    uploadError (response, file, fileList) {
      this.$message.error('上传图片失败！')
    }
  }
};
</script>

<style>
.el-image {
  width: 50px;
  height: 50px;
}
</style>
